<template>
  <div class="chapter-manager">
    <h3 class="chapter-manager-title">章节管理</h3>
    <!-- 章节列表 -->
    <div class="chapters-container">
      <div v-for="(chapter, chapterIndex) in chapters" :key="chapter.id" class="chapter-item">
        <!-- 章节头部 -->
        <div class="chapter-header">
          <div class="chapter-info">
            <el-input
              v-model="chapter.name"
              placeholder="章节标题"
              size="small"
              class="chapter-name-input"
              @blur="updateChapterName(chapterIndex)"
            />
            <span class="chapter-duration">{{ getChapterDuration(chapter) }}</span>
          </div>
          <div class="chapter-actions">
            <el-button type="primary" size="small" @click="addSection(chapterIndex)">
              <el-icon><Plus /></el-icon> 添加小节
            </el-button>
            <el-button size="small" @click="deleteChapter(chapterIndex,chapter)">
              <el-icon><Delete /></el-icon> 删除章节
            </el-button>
          </div>
        </div>
        
        <!-- 小节列表 -->
        <div class="sections-container">
          <div
            v-for="(section, sectionIndex) in chapter.sections"
            :key="section.id"
            class="section-item"
          >
            <div class="section-info">
              <el-input
                v-model="section.name"
                placeholder="小节标题"
                size="small"
                class="section-name-input"
                @blur="updateSection(sectionIndex, chapterIndex)"
              />
              
              <!-- 视频上传区域 -->
              <div class="section-video">
                <el-upload
                  class="video-uploader"
                  action=""
                  :show-file-list="false"
                  :before-upload="beforeVideoUpload"
                  :http-request="options => viewUpload(options, sectionIndex, chapterIndex)"
                >
                  <el-button size="small" :disabled="!!section.videoUrl">
                    <el-icon><Upload /></el-icon>
                    {{ section.videoUrl ? '重新上传' : '上传视频' }}
                  </el-button>
                </el-upload>
                <el-input
                  v-model="section.duration"
                  placeholder="时长 (HH:MM:SS)"
                  size="small"
                  class="duration-input"
                  @blur="updateSection(sectionIndex, chapterIndex)"
                />
                <el-switch
                  v-model="section.free"
                  inline-prompt
                  active-text="可预览"
                  inactive-text="需购买"
                  @change="updateSection(sectionIndex, chapterIndex,section,section.free)"
                />
              </div>
              <!-- 已上传的媒体预览 -->
              <div v-if="section.videoUrl" class="media-preview">
                <div class="video-preview">
                  <video :src="section.videoUrl" controls class="preview-video">您的浏览器不支持视频播放</video>
                </div>
              </div>
            </div>
            
            <div class="section-actions">
              <el-button size="small" @click="moveSection(sectionIndex, chapterIndex, -1)" :disabled="sectionIndex === 0">
                <el-icon><ArrowUp /></el-icon> 上移
              </el-button>
              <el-button size="small" @click="moveSection(sectionIndex, chapterIndex, 1)" :disabled="sectionIndex === chapter.sections.length - 1">
                <el-icon><ArrowDown /></el-icon> 下移
              </el-button>
                <el-button size="small" type="danger" @click="deleteSection(sectionIndex, chapterIndex,section)">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加章节按钮 -->
    <div class="add-chapter-container">
      <el-button type="primary" @click="addChapter">
        <el-icon><Plus /></el-icon> 添加章节
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {ref, watch} from 'vue'
import { Plus, Delete, Upload, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {mp4Upload} from "@/api/FileUpload.js";
import {delSections,updateSections} from "@/api/Sections.js";
import {delChapter} from "@/api/Chapters.js";
// 定义props
const props = defineProps({
  sonCourses:{
    required:true
  },
  initialChapters: {
    type: Array,
    default: () => []
  }
})

// 定义emit
const emit = defineEmits(['update:chapters'])

// 章节数据
const chapters = ref([])

// 监听章节变化，同步到父组件
watch(() => [...chapters.value||[]], (newChapters) => {
  emit('update:chapters', newChapters)
}, { deep: true })

// 添加对props.sonCourses的监听，确保在sonCourses变化时重新获取数据
watch(() => props.sonCourses, (newCourses, oldCourses) => {
  console.log(`course发生变化: 从 ${oldCourses} 变为 ${newCourses}`)
  //以下两个写法都可以
  //chapters.value = props.sonCourses.chaptersList
  chapters.value = newCourses.chaptersList
}, { immediate: true }) // immediate: true 确保在组件挂载时立即执行一次

// 添加章节
const addChapter = () => {
  //添加真实的章节的信息
  if(chapters.value==null){
    chapters.value=[]
  }
  const newChapter = {
    name: `第${chapters.value.length + 1}章：新章节`,
    chapterDuration:"00:00", //章节的时长
    sections: []
  }
  chapters.value.push(newChapter)
}

// 删除章节
const deleteChapter = (index,chapterObj) => {
  //先判断(章节中是否有小节)在删除
  if(chapterObj.sections.length!=0){
    ElMessage.warning('章节中关联小节，请删除小节后再删除章节')
    return ;
  }
  chapters.value.splice(index, 1)
  //数据库删除  id
   delChapter(chapterObj.id).then(res=>{
     if(res.code===200){
       ElMessage.success('章节删除成功')
       return ;
     }
     ElMessage.error('章节删除失败')
   })

}

// 更新章节名称
const updateChapterName = (index) => {
  ElMessage.success('章节名称更新成功')
}

// 添加小节
const addSection = (chapterIndex) => {
  const chapter = chapters.value[chapterIndex]
  //添加真实的小节信息
  const newSection = {
    name: `${chapterIndex + 1}.${chapter.sections.length + 1} 新小节`,
    videoUrl: '',
    duration: '00:00',
    free: false
  }
  chapter.sections.push(newSection)
  ElMessage.success('小节添加成功')
}

// 删除小节
const deleteSection = (sectionIndex, chapterIndex,section) => {
  console.log(section)
  const chapter = chapters.value[chapterIndex]
  chapter.sections.splice(sectionIndex, 1)
  //物理删除-->去数据库删除,知道要删除小节的id的值
  delSections({id:section.id,videoUrl:section.videoUrl}).then(res=>{
    if(res.code===200){
      ElMessage.success('小节删除成功')
      return ;
    }
    ElMessage.error('小节删除失败')
  })
}

// 更新小节信息
const updateSection = (sectionIndex, chapterIndex,section,free) => {
  console.log(free)
  updateSections({
    id:section.id,
    free:free
  }).then(res=>{
    if(res.code===200){
      ElMessage.success('小节状态更新成功')
      return ;
    }
    ElMessage.error('小节状态更新失败')
  })

}

// 移动小节
const moveSection = (sectionIndex, chapterIndex, direction) => {
  const chapter = chapters.value[chapterIndex]
  const newIndex = sectionIndex + direction
  if (newIndex < 0 || newIndex >= chapter.sections.length) {
    return
  }
  // 交换位置
  const temp = chapter.sections[sectionIndex]
  chapter.sections[sectionIndex] = chapter.sections[newIndex]
  chapter.sections[newIndex] = temp
  
  ElMessage.success('小节位置已调整')
}
//格式化秒数为 HH:MM:SS
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600).toString().padStart(2, '0')
  const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0')
  const secs = Math.floor(seconds % 60).toString().padStart(2, '0')
  return `${hours}:${minutes}:${secs}`
}

//获取视频文件的实际时长
const getVideoDuration = (file) => {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.preload = 'metadata'
    
    video.onloadedmetadata = () => {
      // 创建一个临时的Object URL，但不会添加到DOM中
      URL.revokeObjectURL(video.src)
      resolve(video.duration)
    }
    
    video.onerror = () => {
      URL.revokeObjectURL(video.src)
      reject(new Error('无法获取视频时长'))
    }
    
    // 为了获取本地文件的时长，我们需要创建一个临时的Object URL
    const objectUrl = URL.createObjectURL(file)
    video.src = objectUrl
  })
}

//自定义上传
const  viewUpload=  async (options, sectionIndex, chapterIndex)=>{
  console.log("视频上传开始.....")
  console.log("文件信息:", options.file)
  console.log("小节索引:", sectionIndex, "章节索引:", chapterIndex)
  const formData = new FormData()
  formData.append('file', options.file)
  try {
    // 1. 首先获取本地视频文件的实际时长
    let videoDuration = null
    try {
      videoDuration = await getVideoDuration(options.file)
      console.log("视频实际时长(秒):", videoDuration)
    } catch (durationError) {
      console.warn("获取视频时长失败，将使用默认值:", durationError)
    }
    
    // 2. 上传视频到服务器
    const res = await mp4Upload(formData)
    console.log("上传响应完整数据:", res)
    
    // 3. 获取并更新section对象
    const section = chapters.value[chapterIndex].sections[sectionIndex]
    // 4. 设置URL和计算的时长
    section.videoUrl = res.data
    // 5. 如果成功获取了时长，则设置到section中
    if (videoDuration !== null && !isNaN(videoDuration)) {
      const formattedDuration = formatDuration(videoDuration)
      section.duration = formattedDuration
    }
    ElMessage.success('视频上传成功，预览已生成')
  } catch (error) {
    console.error("视频上传错误:", error)
    ElMessage.error('视频上传失败: ' + error.message)
  }
}

// 视频上传前校验
const beforeVideoUpload = (file) => {
  const isMP4 = file.type === 'video/mp4' || file.type === 'video/webm'
  const isLt200M = file.size / 1024 / 1024 < 1000
  if (!isMP4) {
    ElMessage.error('上传视频只能是 MP4/WebM 格式!')
  }
  if (!isLt200M) {
    ElMessage.error('上传视频大小不能超过 1000MB!')
  }
  return isMP4 && isLt200M
}

// 计算章节总时长
const getChapterDuration = (chapter) => {
  if (!chapter.sections || chapter.sections.length === 0) {
    return '00:00'
  }
  let totalSeconds = 0
  chapter.sections.forEach(section => {
    if (section.duration) {
      try {
        const parts = section.duration.split(':').map(Number)
        // 处理不同格式的时长：HH:MM:SS 或 MM:SS
        if (parts.length === 3) {
          const [hours, minutes, seconds] = parts
          // 确保所有值都是有效数字
          if (!isNaN(hours) && !isNaN(minutes) && !isNaN(seconds)) {
            totalSeconds += hours * 3600 + minutes * 60 + seconds
          }
        } else if (parts.length === 2) {
          const [minutes, seconds] = parts
          // 确保所有值都是有效数字
          if (!isNaN(minutes) && !isNaN(seconds)) {
            totalSeconds += minutes * 60 + seconds
          }
        }
      } catch (error) {
        console.log('解析时长出错:', error)
      }
    }
  })
  const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0')
  const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0')
  const seconds = (totalSeconds % 60).toString().padStart(2, '0')
  return `${hours}:${minutes}:${seconds}`
}
</script>

<style scoped>
/* 视频预览样式 */
.media-preview {
  margin-top: 10px;
  margin-bottom: 10px;
}

.video-preview {
  background-color: #f5f7fa;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.preview-video {
  width: 100%;
  max-width: 600px;
  max-height: 400px;
  object-fit: contain;
  border-radius: 4px;
}

.video-info {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.video-info span:first-child {
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #e6f7ff;
  color: #1890ff;
}
.chapter-manager {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chapter-manager-title {
  color: #1890ff;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.chapter-item {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 6px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.chapter-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.chapter-name-input {
  width: 300px;
}

.chapter-duration {
  color: #606266;
  font-size: 14px;
}

.chapter-actions {
  display: flex;
  gap: 8px;
}

.sections-container {
  margin-left: 20px;
}

.section-item {
  margin-bottom: 15px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.section-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.section-type-select {
  width: 100px;
}

.section-name-input {
  flex: 1;
  min-width: 200px;
}

.section-video,
.section-document {
  display: flex;
  align-items: center;
  gap: 10px;
}

.duration-input {
  width: 120px;
}

.media-preview {
  width: 100%;
  margin-top: 10px;
  padding: 10px;
  background: #fafafa;
  border-radius: 4px;
}

.preview-video {
  width: 100%;
  max-width: 400px;
  height: auto;
}

.section-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.add-chapter-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chapter-header,
  .section-info {
    flex-direction: column;
    align-items: stretch;
  }
  
  .chapter-name-input {
    width: 100%;
  }
  
  .section-actions {
    justify-content: center;
  }
}
</style>